package org.platform.processor.diagnose.job;


import lombok.extern.slf4j.Slf4j;
import org.platform.core.JobManager;
import org.platform.mo.bussmo.diagnose.test.TestStepParam;
import org.platform.mo.db.FdDiagnoseTestStep;
import org.platform.processor.diagnose.DiagnoseRecordProcessor;
import org.platform.tool.util.ComUtils;
import org.platform.tool.util.DataFrameUtil;
import org.quartz.JobKey;
import org.quartz.SimpleScheduleBuilder;
import org.quartz.SimpleTrigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.JobDetailImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.zeromq.ZMQ;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;


/**
 * 本类用于处理 测试联试单元模块将测试过程信息发送至故障诊断模块
 *
 * @author FengJie
 * @date 2018/8/30
 */
@Component
@Slf4j
public class ReceiveTestStepJob {
    private static final String TOPIC = "TestStep";
    private static final String ADDR = "tcp://127.0.0.1:28881";

    private ZMQ.Socket socket;

    @Autowired
    private DiagnoseRecordProcessor processor;
    @Autowired
    private JobManager job;

    /**
     * 初始化接收线程
     */
    @PostConstruct
    void init() {
        ZMQ.Context context = ZMQ.context(1);
        this.socket = context.socket(ZMQ.SUB);
        socket.connect(ADDR);
        socket.subscribe(TOPIC);
        new ReceiveThread().start();
    }

    class ReceiveThread extends Thread {
        @SuppressWarnings(value = "InfiniteLoopStatement")
        @Override
        public void run() {
            while (true) {
                try {
                    //第一次接收到的是主题  第二次接收到的是内容
                    String topic = socket.recvStr(0);
                    if (TOPIC.equals(topic)) {
                        byte[] recv = socket.recv();
                        //截取固定位数据
                        String data = DataFrameUtil.analysis(recv);
                        TestStepParam.TestStep testStep = TestStepParam.TestStep.parseFrom(data.getBytes());

                        //保存到数据库,并且推动到客服端
                        List<FdDiagnoseTestStep> list = getList(testStep);
                        processor.saveTestStep(list);

                        JobDetailImpl jd = new JobDetailImpl();
                        jd.setJobClass(PromoteTreeDiagnoseDetailJob.class);
                        jd.setKey(JobKey.jobKey(ComUtils.getUUID()));
                        jd.getJobDataMap().put(PromoteTestStepJob.DATA_KEY, list);

                        SimpleTrigger trigger = TriggerBuilder.newTrigger()
                                .withSchedule(SimpleScheduleBuilder.simpleSchedule())
                                .startNow()
                                .build();

                        job.register(jd, trigger);
                    }
                } catch (Exception e) {
                    log.error("解析【任务测试步骤】参数异常:", e);
                }
            }
        }

        /**
         * 测试步骤转换
         *
         * @param testStep 接口中的测试步骤
         * @return 数据库定义的测试步骤
         */
        private List<FdDiagnoseTestStep> getList(TestStepParam.TestStep testStep) {
            List<FdDiagnoseTestStep> list = new ArrayList<>(testStep.getStepsCount());
            testStep.getStepsList().forEach(testStepInfo -> {
                FdDiagnoseTestStep diagnoseTestStep = new FdDiagnoseTestStep();
                diagnoseTestStep.setStationId(testStep.getStationID());
                diagnoseTestStep.setTimeTag(testStep.getTimeTag());
                diagnoseTestStep.setTestPlanId(testStep.getTestPlanID());
                diagnoseTestStep.setTestSubID(testStep.getTestSubID());
                diagnoseTestStep.setTestType(testStep.getTestType());
                diagnoseTestStep.setStepNo(ComUtils.strToInteger(testStepInfo.getStepNo()));
                diagnoseTestStep.setStepName(testStepInfo.getStepName());
                diagnoseTestStep.setStepStatus(ComUtils.strToInteger(testStepInfo.getStepStatus()));
                list.add(diagnoseTestStep);
            });
            return list;
        }
    }

}
